/**
 * 获取当前时间戳
 */
export function getTimeStamp() {
  return new Date().getTime();
}

/**
 * 获取当前格式化时间
 */
export function getDateTime(date: Date | string, format: string) {
  if (date) {
    date = new Date(date);
  } else {
    date = new Date();
  }
  if (!format) {
    format = "yyyy-MM-dd hh:mm:ss";
  }
  const o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
    "q+": Math.floor((date.getMonth() + 3) / 3),
    S: date.getMilliseconds()
  } as any;
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (date.getFullYear() + "").substring(4 - RegExp.$1.length));
  }
  for (const k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substring(("" + o[k]).length));
    }
  }
  return format;
}

/**
 * 生成指定长度随机字符串
 */
export function getRandomString(length: number) {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  const maxPos = chars.length;
  let pwd = "";
  for (let i = 0; i < length; i++) {
    if (i === 0) {
      pwd += chars.charAt(Math.floor(Math.random() * (maxPos - 10)));
    } else {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
  }
  return pwd;
}

/**
 * 数组对象某个属性去重
 */
export function uniqueObject(arr: Array<any>, key: string) {
  const objs = {} as any;
  return arr.reduce((cur: any, next: any) => {
    if (!objs[next[key]]) {
      objs[next[key]] = true;
      cur.push(next);
    }
    return cur;
  }, []);
}

/**
 * 对象深层拷贝不包含函数和undefined
 */
export function deepClone(obj: any) {
  return JSON.parse(JSON.stringify(obj));
}

/**
 * 对象深层递归拷贝包含函数和undefined
 */
export function deepCloneRecursive(obj: any) {
  const result: any = Array.isArray(obj) ? [] : {};
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      if (typeof obj[key] === "object") {
        if (obj[key] === null) {
          result[key] = null;
        } else {
          result[key] = deepCloneRecursive(obj[key]);
        }
      } else {
        result[key] = obj[key];
      }
    }
  }
  return result;
}

/**
 * 防抖
 */
export function debounceFn(fn: any, delay: number) {
  let timer: number | null = null;
  return function () {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      // eslint-disable-next-line prefer-rest-params
      fn.apply(this, arguments);
      timer = null;
    }, delay);
  };
}

/**
 * 节流
 */
export function throttlingFn(fn: any, interval: number) {
  let startTime = 0;
  return function () {
    const nowTime = new Date().getTime();
    const waitTime = interval - (nowTime - startTime);
    if (waitTime <= 0) {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      // eslint-disable-next-line prefer-rest-params
      fn.apply(this, arguments);
      startTime = nowTime;
    }
  };
}

/**
 * 下载txt
 */
export function downloadTxt(text: string, fileName: string) {
  const element = document.createElement("a");
  element.setAttribute("href", "data:text/plain;charset=utf-8," + encodeURIComponent(text));
  fileName = fileName + ".txt";
  element.setAttribute("download", fileName);
  element.style.display = "none";
  element.click();
}

/**
 * 上传txt
 */
export function uploadingTxt(cb: any) {
  const element = document.createElement("input") as any;
  element.type = "file";
  element.accept = ".txt";
  element.click();
  element.addEventListener("change", () => {
    readTxt(element.files[0], (result: string) => {
      if (result) {
        cb(result);
      } else {
        cb("");
      }
    });
  });
}

/**
 * 读取txt
 */
export function readTxt(file: File, cb: any) {
  const reader = new FileReader();
  reader.onload = function (event) {
    if (event && event.target && event.target.result) {
      cb(event.target.result);
    } else {
      cb("");
    }
  };
  reader.readAsText(file);
}
